package com.erp.erp_ui.User;

import com.alibaba.fastjson.JSONObject;
import com.erp.erp_entitys.Account.AccountEntity;
import com.erp.erp_entitys.Department.DepartmentEntity;
import com.erp.erp_entitys.Department.DepartmentExample;
import com.erp.erp_entitys.LogDB.LogDBEntity;
import com.erp.erp_entitys.Menum.MenuEntity2;
import com.erp.erp_entitys.Menum.MenumEntity;
import com.erp.erp_entitys.Resource.ResourceEntity;
import com.erp.erp_entitys.Role.RoleEntity;
import com.erp.erp_entitys.Role.RoleExample;
import com.erp.erp_entitys.User.*;
import com.erp.erp_servers.Account.IAccountService;
import com.erp.erp_servers.Department.IDepartmentService;
import com.erp.erp_servers.Role.IRoleService;
import com.erp.erp_servers.RoleGroup.IRoleGroupService;
import com.erp.erp_servers.User.IUserService;
import com.erp.erp_servers.log.ILogDBService;
import com.erp.erp_ui.base.Base;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.erp.utils.StringUtil;
import com.erp.utils.WebApiUtils;
import com.ys.openapi.organization.department.User;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName UserControl
 * @Description TODO
 * @Author songjizhen
 * @Date 2020-07-03 23:07
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "user")
 public class UserControl extends Base {
    @Autowired
    IUserService userService;
    @Autowired
    IAccountService accountService;

    @Autowired
    IRoleService roleService;
    @Autowired
    IRoleGroupService roleGroupService;
    @Autowired
    IDepartmentService departmentService;
    @Autowired
    ILogDBService logDBService;
    //云枢user
    User user1=new User();
    /**
     * 根据员工编码获取员工信息
     * @param code
     * @return
     */
    @RequestMapping(value = "selectByCode",method = RequestMethod.POST)
    @ResponseBody
     public R selectByCode(String code) {
        try {
            UserAndLogVo userAndLogVo=new UserAndLogVo();

            //用户信息
            UserEntity userEntity = userService.selectUserByCode(code);
            userAndLogVo.setUser(userEntity);

            //用户操作日志
            LogDBEntity logDBEntity=new LogDBEntity();
            logDBEntity.setParams("employeeNo='"+code+"'");
            List<LogDBEntity> query = logDBService.query(logDBEntity);

            List<UserLog> userLogList=new ArrayList<>();
            for (LogDBEntity d:query) {
                UserLog userLog=new UserLog();
                userLog.setOperationType(d.getType());
                userLog.setOperatorName(d.getUserName());
                userLog.setOperationDate(d.getInTime());

                String par=d.getParams();
                String str=par.substring(par.indexOf("id"),par.indexOf(", deptIds"));
                String array[]=str.split(", ");
                String roles=par.substring(par.indexOf("roleIds"),par.indexOf(", UserUnionExtAttrModel"));

                String customerRole="";
                if (par.contains("customerRole=")){
                    customerRole=par.substring(par.indexOf("customerRole"));
                }

                List<String> stringAsList=new ArrayList<>(Arrays.asList(array));
                stringAsList.add(roles);
                if (StringUtils.isNotEmpty(customerRole)){
                    stringAsList.add(customerRole);
                }


                String content="";
                for (String p:stringAsList) {
                    if (p.lastIndexOf("name")==0){
                        content+="用户名称："+ p.substring(p.indexOf("'")+1, p.lastIndexOf("'"))+"，";
                    }else if (p.lastIndexOf("newEmail")==0){
                        content+="邮件地址："+ p.substring(p.indexOf("'")+1, p.lastIndexOf("'"))+"，";
                    }else if (p.lastIndexOf("departmentId")==0){
                        content+="所属部门:"+ p.substring(p.indexOf("'")+1, p.lastIndexOf("'"))+"，";
                    }else if (p.lastIndexOf("newMsn")==0){
                        content+="是否管理层："+ p.substring(p.indexOf("'")+1, p.lastIndexOf("'"))+"，";
                    }else if (p.lastIndexOf("roleIds")==0){
                        content+="角色组："+ p.substring(p.indexOf("=")+1, p.lastIndexOf("]")+1)+"，";
                    }else if (p.lastIndexOf("customerRole")==0){
                        content+="管理组："+ p.substring(p.indexOf("=")+1, p.lastIndexOf("]")+1)+"，";
                    }
                }
                userLog.setModifyContent(content);
                userLogList.add(userLog);
            }
            userAndLogVo.setUserLogList(userLogList);

            return R.build(userAndLogVo);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 获取部门下所有员工
     * @param departmentCode
     * @return
     */
    @RequestMapping(value = "selectByPage",method = RequestMethod.POST)
    @ResponseBody
     public R<List<UserEntity>> selectByPage(String departmentCode){
        try {
            List<UserEntity> userEntities = userService.selectByExample(departmentCode);
            return R.build(userEntities);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    @RequestMapping(value = "selectByCodeByPage")
    @ResponseBody
    public R<List<UserEntity>> selectByCodeByPage(String departmentCode,String name){
        try {
            List<UserEntity> userEntities = userService.selectByExample(departmentCode,name);

            return R.build(userEntities);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }
    /**
     * 获取部门下所有员工
     * @param departmentCode
     * @return
     */
    @RequestMapping(value = "selectByDcode",method = RequestMethod.POST)
    @ResponseBody
    public R<List<UserEntityVO>> selectByDcode(String departmentCode,String name){
        try {
            List<UserEntity> userEntities = userService.selectByExample(departmentCode,name);

            List<UserEntityVO> list=new ArrayList<>();
            //获取帐号列表
            AccountEntity accountEntity=new AccountEntity();
            List<AccountEntity> accountEntities = accountService.selectByExample(accountEntity);
            Map<String,String> map=new HashMap<>();
            for(int i=0;i<accountEntities.size();i++){
                AccountEntity ae = accountEntities.get(i);
                map.put(ae.getUsercode(),ae.getCode());
            }
            //获取角色与角色组列表
            RoleEntity record=new RoleEntity();
            List<RoleEntity> roleEntities = roleService.selectByExample(record);
           /* RoleGroupEntity rgroup=new RoleGroupEntity();
            List<RoleGroupEntity> roleGroupEntities = roleGroupService.selectByExample(rgroup);*/
            Map<String,String> roleMap=new HashMap<>();
           /* Map<String,String> roleGroupMap=new HashMap<>();*/
            for(int i=0;i<roleEntities.size();i++){
                RoleEntity re = roleEntities.get(i);
                roleMap.put(re.getCode(),re.getName());
            }
          /*  for(int i=0;i<roleGroupEntities.size();i++){
                RoleGroupEntity re = roleGroupEntities.get(i);
                roleGroupMap.put(re.getCode(),re.getName());
            }*/
            //组装vo列表
            for(int i=0;i<userEntities.size();i++){
                UserEntity ue=userEntities.get(i);
                String jb=JSONObject.toJSONString(ue);
                UserEntityVO userEntityVO = JSONObject.parseObject(jb, UserEntityVO.class);
                String roles=userEntityVO.getRoles();
                if(StringUtils.isNotEmpty(roles)){
                    String[] splits = roles.split(",");
                    String role="";
                    for(int n=0;n<splits.length;n++){
                        if(n==splits.length-1){
                            if(null !=roleMap.get(splits[n])){
                                role=role+roleMap.get(splits[n]);
                            }
                        }else{
                            if(null !=roleMap.get(splits[n])){
                                role=role+roleMap.get(splits[n])+",";
                            }
                        }

                    }
                    userEntityVO.setRoles(role);
                }
                if(null ==map.get(userEntityVO.getCode())){
                    userEntityVO.setFlag("true");
                }else{
                    userEntityVO.setFlag("false");
                }

                list.add(userEntityVO);
            }
            return R.build(list);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 根据主键删除用户,逻辑删除
     * @param id
     * @return
     */
    @RequestMapping(value = "deleteByKey",method = RequestMethod.POST)
    @ResponseBody
     public R<Integer> deleteByKey(String id) {
        try {

            UserEntity userEntity=new UserEntity();
            userEntity.setId(id);
            userEntity.setDeleteflag(true);
            int num = userService.updateByPrimaryKeySelective(userEntity);

            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "deleteByIDS",method = RequestMethod.POST)
    @ResponseBody
    public R<Integer> deleteByIDS(String[] ids){

        try {
            UserEntity user = (UserEntity)this.getBean("user");

            UserEntityExample example=new UserEntityExample();
            UserEntityExample.Criteria criteria = example.createCriteria();

            List<String> list=new ArrayList<>();
            for(int i=0;i<ids.length;i++){
                list.add(ids[i].replace("\"","").replace("[","").replace("]",""));
            }
            criteria.andIdIn(list);
            List<UserEntity> userEntities = userService.selectByExample(example);

            int num = userService.deleteByExample(list);
            //同步云枢
            try {
                com.ys.openapi.organization.entity.UserEntity u=new com.ys.openapi.organization.entity.UserEntity();
                WebApiUtils wau=new WebApiUtils();
                for(int i=0;i<userEntities.size();i++){
                    u.setName(userEntities.get(i).getName());
                    user1.deleteuser(u, wau.getTokenString());
                    logDBService.insert(new LogDBEntity(user.getName()+"("+user.getCode()+")","delete(删除)","用户=>"+u.toString()));
                }
            }catch (Exception e){
                num=num+10000;
            }
            //结束
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 新增员工
     * @param record
     * @return
     */
    @RequestMapping(value = "insert",method = RequestMethod.POST)
    @ResponseBody
     public R<Integer> insert(@RequestBody UserEntity record) {

        try {
            UserEntity user = (UserEntity)this.getBean("user");
            record.setCreator(user.getCode());
            record.setCreateTime(new Date());
            record.setId(System.currentTimeMillis()+"");
            int num = userService.insertSelective(record);
            try {
                //同步云枢
                String[] roles=record.getRoles().split(",");
                List<String> roleList=new ArrayList<String>();
                for(int i=0;i<roles.length;i++){
                    roleList.add(roles[i]);
                }
                RoleExample examplerole=new RoleExample();
                RoleExample.Criteria criteria1 = examplerole.createCriteria();
                criteria1.andCodeIn(roleList);
                List<RoleEntity> roleEntities = roleService.selectByExample(examplerole);
                List<String> listName=new ArrayList<>();
                for(int i=0;i<roleEntities.size();i++){
                    listName.add(roleEntities.get(i).getName());
                }

                DepartmentExample example=new DepartmentExample();
                DepartmentExample.Criteria criteria = example.createCriteria();
                criteria.andCodeEqualTo(record.getDepartmentCode());
                List<DepartmentEntity> departmentEntities = departmentService.selectByExample(example);
                String departName=departmentEntities.get(0).getName();

                List<String> customerRoles = Arrays.asList(record.getCustomerRole().split(","));
                List<UserEntity> userList = userService.getUserByUserCodeList(customerRoles);
                List<String> roleUserNames = userList.stream().map(p -> p.getName()).collect(Collectors.toList());

                WebApiUtils wau=new WebApiUtils();
                com.ys.openapi.organization.entity.UserEntity u=new com.ys.openapi.organization.entity.UserEntity();
              /*{"departmentId":"2c2c80867ab40ee9017aca0657a30636","deptIds":[],"username":"用户账号12","name":"用户姓名12",
            "roleIds":[],"mobile":"18653178230","officePhone":"","email":"","employeeNo":"234599",
            "entryDate":"","imgUrl":"","imgUrlId":"","gender":"MALE"}  //    [OTHER, FEMALE, MALE],*//*
                 *//*  {"departmentId":"主部门ID","deptIds":"兼职部门ID集合","username":"用户账号","name":"用户姓名","roleIds":"角色ID集合",
            "mobile":"手机号","officePhone":"办公电话","email":"邮箱","employeeNo":"员工编号","entryDate":"入职时间",
            "imgUrl":"头像url","imgUrlId":"头像Id","gender":"性别"}*/

                u.setDepartmentId(departName);
                u.setUsername(record.getCode());
                u.setName(record.getName());
                u.setEmployeeNo(record.getCode());
                int sex=record.getSex();
                u.setGender(sex==1?"MALE":sex==0?"FEMALE":"OTHER");
                //性别（0：女；1：男）
                u.setMobile(record.getPhone());
                u.setDeptIds(new ArrayList());
                u.setEmail("");
                u.setEntryDate("");
                u.setImgUrl("");
                u.setImgUrlId("");
                u.setOfficePhone("");
                u.setNewEmail(record.getEmail());
                u.setNewMsn(record.getMsn());
                u.setCustomerRole(roleUserNames);
                u.setRoleIds(listName);
                u.setUserUnionExtAttrModel(new ArrayList());
                user1.addUser(u,wau.getTokenString());
                logDBService.insert(new LogDBEntity(user.getName()+"("+user.getCode()+")","insert(新增)","用户=>"+u.toString()));
                //结束
            }catch (Exception e){
                num=num+10000;
            }

            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
           return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据主键更新用户
     * @param record
     * @return
     */
    @RequestMapping(value = "updateByKey",method = RequestMethod.POST)
    @ResponseBody
     public R<Integer> updateByKey(@RequestBody UserEntity record) {

        try {
            UserEntity user = (UserEntity)this.getBean("user");
            record.setCreator(user.getCode());
            record.setCreateTime(new Date());
            UserEntity userEntity = userService.selectUserByCode(record.getCode());
            int num = userService.updateByPrimaryKeySelective(record);
            try {
                //开始同步云枢
                String[] roles=record.getRoles().split(",");
                List<String> roleList=new ArrayList<String>();
                for(int i=0;i<roles.length;i++){
                    roleList.add(roles[i]);
                }
                RoleExample examplerole=new RoleExample();
                RoleExample.Criteria criteria1 = examplerole.createCriteria();
                criteria1.andCodeIn(roleList);
                List<RoleEntity> roleEntities = roleService.selectByExample(examplerole);
                List<String> listName=new ArrayList<>();
                for(int i=0;i<roleEntities.size();i++){
                    listName.add(roleEntities.get(i).getName());
                }

                DepartmentExample example=new DepartmentExample();
                DepartmentExample.Criteria criteria = example.createCriteria();
                criteria.andCodeEqualTo(record.getDepartmentCode());
                List<DepartmentEntity> departmentEntities = departmentService.selectByExample(example);
                String departName=departmentEntities.get(0).getName();

                List<String> customerRoles = Arrays.asList(record.getCustomerRole().split(","));
                List<UserEntity> userList = userService.getUserByUserCodeList(customerRoles);
                List<String> roleUserNames = userList.stream().map(p -> p.getName()).collect(Collectors.toList());


                WebApiUtils wau=new WebApiUtils();
                com.ys.openapi.organization.entity.UserEntity u=new com.ys.openapi.organization.entity.UserEntity();
                u.setDepartmentId(departName);
                u.setUsername(record.getCode());
                u.setName(record.getName());
                u.setEmployeeNo(record.getCode());
                int sex=record.getSex();
                u.setGender(sex==1?"MALE":sex==0?"FEMALE":"OTHER");
                //性别（0：女；1：男）
                u.setMobile(record.getPhone());
                u.setDeptIds(new ArrayList());
                u.setEmail(userEntity.getName());//用此列传值 到接口
                u.setEntryDate("");
                u.setImgUrl("");
                u.setImgUrlId("");
                u.setOfficePhone("");
                u.setNewEmail(record.getEmail());
                u.setNewMsn(record.getMsn());
                u.setCustomerRole(roleUserNames);
                u.setRoleIds(listName);
                u.setUserUnionExtAttrModel(new ArrayList());
                user1.modifyuser(u,wau.getTokenString());
                logDBService.insert(new LogDBEntity(user.getName()+"("+user.getCode()+")","update(更新)","用户=>"+u.toString()));
                //结束
            }catch (Exception e){
                num=num+10000;
            }

            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据userCode获取用户菜单
     * @return
     */
    @RequestMapping(value = "getMenumByUserCode",method = RequestMethod.POST)
    @ResponseBody
     public R<List<MenumEntity>> getMenumByUserCode(){
        try {
            UserEntity user =(UserEntity) this.getBean("user");
            List<MenumEntity> allResourceByUser = userService.getAllResourceByUser(user);

            return R.build(allResourceByUser);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据userCode获取用户菜单
     * @return
     */
    @RequestMapping(value = "getMenumByUserCode2",method = RequestMethod.POST)
    @ResponseBody
    public R<MenuEntity2> getMenumByUserCode2(){
        try {
            UserEntity user =(UserEntity) this.getBean("user");
            List<MenuEntity2> allResourceByUser = userService.getAllResourceByUser2(user);
            if(allResourceByUser.size()==0){
                return R.build(null);
            }
            return R.build(allResourceByUser.get(0));
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据菜单父节点获取其下子菜单
     * @param pid
     * @return
     */
    @RequestMapping(value = "getMenumByPid",method = RequestMethod.POST)
    @ResponseBody
     public R<List<ResourceEntity>> getMenumByPid(String pid){
        try {
            List<ResourceEntity> menumByPid = userService.getMenumByPid(pid);
            return R.build(menumByPid);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }

    /**
     * 根据标签角色类型获取当前用户是否具有此标签角色的权限
     * @param list 标签角色code列表
     * @return
     */

    @RequestMapping(value = "getRoleByRoleType",method = RequestMethod.POST)
    @ResponseBody
     public R<Map<String,Boolean>> getRoleByRoleType(List<String> list){//角色类型（1:资源；2:标签、按钮）
        try {
            UserEntity user =(UserEntity) this.getBean("user");
            String roles=user.getRoles();
            Map<String,Boolean> map=new HashMap<String,Boolean>();
            for(int i=0;i<list.size();i++){
                if(roles.indexOf(list.get(i)) !=-1){
                    map.put(list.get(i),true);
                }else{
                    map.put(list.get(i),false);
                }
            }

            return R.build(map);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 获取用户所有角色
     * @return
     */
    @RequestMapping(value = "getAllRoleByUserCode",method = RequestMethod.POST)
    @ResponseBody
     public R<List<RoleEntity>> getAllRoleByUserCode(){
        try {
            UserEntity user =(UserEntity) this.getBean("user");
            List<RoleEntity> allRoleByUserCode = userService.getAllRoleByUserCode(user);
            return R.build(allRoleByUserCode);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }
    public  R getUserTree(){

        return null;
    }

    /**
     * 查询用户name和code
     * @return 用户列表
     */
    @RequestMapping(value = "getAllUserNameAndCode")
    @ResponseBody
    @ApiOperation(value = "查询用户name和code", notes = "查询用户name和code", httpMethod = "POST")
    public R<List<UserEntity>> getAllUserNameAndCode(){
        try {
            Object cacheUser = this.getBean("user");
            if (null!=cacheUser){
                UserEntity user = (UserEntity )cacheUser;
                List<UserEntity> allUserList = userService.getAllUserNameAndCode();
                if (allUserList==null){
                    return  R.buildError(ResultStatusEnum.SELECT_LIST_ISNULL_ERROR);
                }
                return R.build(allUserList);
            }else{
                return  R.buildError(ResultStatusEnum.TOKEN_FAILURE);
            }
        }catch (Exception e){
            e.printStackTrace();
            return  R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 获取所用用户
     * @return
     */
    @RequestMapping(value = "getAllUser")
    @ResponseBody
    public R<List<UserEntity>> getAllUser(){
        return R.build(userService.getAllUser());
    }


    /**
     *
     * 判断该用户是否拥有 用户设置删除按钮显示(YHSZSCANXS001) 角色
     */
    @RequestMapping("isContainsRoleUser")
    @ResponseBody
    public R isContainsRoleUser(){
        try {
            UserEntity user = (UserEntity) this.getBean("user");
            if (user.getRoles().contains("YHSZSCANXS001")){
                return R.build(true);
            }else {
                return R.build(false);
            }
        } catch (Exception e) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

    }

}
